#!/data/Software/mydan/perl/bin/perl -I/data/Software/mydan/CI/lib -I/data/Software/mydan/CI/private/lib
use strict;
use warnings;
use POSIX;
use Logs;
use FindBin qw( $RealBin );
use Temp;
use MIME::Base64;
use Code;

$| ++;

=head1 SYNOPSIS

    db => $mysql,
    logs => 日志对象

    # projectid addr ticketid rely name(版本信息可能为空) temp(logs目录下的临时目录名) uuid

=cut

return sub
{
    my %param = @_;

    my ( $db, $logs, $projectid, $addr, $ticketid, $rely, $name, $temp, $uuid )
        = @param{qw(db logs projectid addr ticketid rely name temp uuid )};

    $logs = Logs->new( 'code.build.dump.pull.git' ) unless $logs;

    my $ssh_key;

    if( $ticketid )
    {
        my $x = eval{ $db->query( "select ticket from ticket where id='$ticketid' and type='SSHKey'" )};  
        $logs->die( "get data from ticket fail:$@" ) if $@;
        $ssh_key = $x->[0][0] if @$x;
    }

    #TODO
    #my $ctrl = $ssh_key ? "$RealBin/../../dan/tools/git -i " . Temp->new( chmod => 0600 )->dump( decode_base64( $ssh_key ) ) : 'git';
    my $ctrl = $ssh_key ? "$RealBin/../../dan/tools/git -i " . Temp->new( chmod => 0600 )->dump( $ssh_key ) : 'git';

    my $temppath = "$RealBin/../logs/$temp/$uuid";
    if( -d $temppath )
    {
        my $user = `id -un`;chop $user;
        my $sudo = $user eq 'root' ? '' : 'sudo ';
        $logs->die( "clean old temppath fail:$!" ) if system "${sudo}rm -rf '$temppath'";
    }

    $logs->die( "mkdir temppath fail:$!" ) if system "mkdir -p '$temppath'";


    my ( $dumptags, $version ) = ( '', 'release' );
    $name = '' unless defined $name;
    if( $name )
    {
        $logs->die( "name format error" ) unless $name =~ /^[a-zA-Z0-9\.\-_]+$/;
        ( $dumptags, $version ) = ( "-b $name", $name );
    }

    my $tagger;
    my $tag_info = '';
    if( $name =~ /^release-testonly-[0-9a-z]{40}/ )
    {
        my ( $commitid, $event_name, $branch );

        if( $name =~ /^release-testonly-([0-9a-z]{40})_([01]{1})-([a-zA-Z0-9][a-zA-Z0-9\-\._])$/ )
        {
            ( $commitid, $event_name, $branch ) = ( $1, $2, $3 );
            $event_name = $event_name ? 'create' : 'delete';
        }
        elsif( $name =~ /^release-testonly-([0-9a-z]{40})-([a-zA-Z0-9][a-zA-Z0-9\-\._]+)$/ )
        {
            ( $commitid, $event_name, $branch ) = ( $1, 'push', $2 );
        }
        elsif( $name =~ /^release-testonly-([0-9a-z]{40})$/ )
        {
            ( $commitid, $event_name, $branch ) = ( $1, 'push', 'master' );
        }
        else
        {
            $logs->die( "name format error" );
        }

        $branch =~ s#\._\.#/#g;

        if( $event_name eq 'delete' )
        {
            $logs->die( "clone error:$!" )
                if system "cd '$temppath' && rm -rf data data.tmp info && mkdir data && mkdir info && echo '$version' > info/version && echo '$branch' > info/branch && echo '$event_name' > info/event_name";
        }
        else
        {
            $logs->die( "clone error:$!" )
                if system "cd '$temppath' && rm -rf data data.tmp info && $ctrl clone --progress -b $branch --recursive $addr data.tmp && mkdir -p info && cd data.tmp && git reset --hard $commitid && cd .. && mv data.tmp/.git info/ && mv data.tmp data && echo '$version' > info/version && echo '$branch' > info/branch && echo '$event_name' > info/event_name";
        }

        my $t = eval{ $db->query( "select `tagger` from version where projectid='$projectid' and name='$name'" )};  
        $logs->die( "get tagger from version  fail:$@" ) if $@;
        $tagger = $t->[0][0] if $t && ref $t && ref $t->[0];
    }
    else
    {
        
        my @cacheid = `cat /etc/ci.cache 2>/dev/null`;
        chomp @cacheid;
        if( grep{ $projectid eq $_ }@cacheid )
        {
            print "get git data from cache\n";
            eval{ Code->new( "build.plugin/dump.plugin/gitclonebycache" )->run( ctrl => $ctrl, addr => $addr, tag => $name, logs => $logs, topath => $temppath ); };
            $logs->die( "run code.build.dump.gitclonebycache fail:$@" ) if $@;
            $logs->die( "echo version error:$!" ) if system "echo '$version' > $temppath/info/version";
        }
        else
        {

            $logs->die( "clone error:$!" )
                if system "cd '$temppath' && rm -rf data data.tmp info && $ctrl clone --progress $dumptags --recursive $addr data.tmp && mkdir -p info && mv data.tmp/.git info/ && mv data.tmp data && echo '$version' > info/version";

        }

        my $info = `cd '$temppath/info' && $ctrl show  -s --format="%ce" $name`;
        Encode::_utf8_on($info);
        print "git info: $info\n";

        my @info_list = split /\n/, $info;
        if (@info_list > 1) {
            $tag_info = $info_list[-2].$info_list[-1];
        }
        my @m;
        if( $info =~ /deploy\s*:\s*([\w\.]+\@gmail\.com|[\w\.]+\@163\.com)/ )
        {
            @m = ( $1 );
        }
        else
        {
            @m = grep{ $_ ne 'lijinfeng2011@gmail.com' } $info =~ /[\w\.\@]+\.com/g;
            unless( @m )
            {
                my @info = grep{ $_ =~ /^[\w\.\@]+$/ }split /\n/, $info;
                push @m, $info[-1] if $info[-1];
            }
        }
        $tagger = $m[0];
    }

    unless( defined $tagger && $tagger =~ /^[a-zA-Z0-9\.\@\-_]+$/ )
    {
        print "get tagger fail,Switch to default: lijinfeng2011\@gmail.com\n";
        $tagger = 'lijinfeng2011@gmail.com';
    }

    $tag_info =~ s/$tagger//g;
    $logs->die( "write tagger info fail:$!" )if system "echo '$tagger' > '$temppath/info/tagger'";
    $logs->die( "write tag_info info fail:$!" )if system "echo '$tag_info' > '$temppath/info/taginfo'";

}


